from django.db import connection
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

def build_menu(request):

    user = request.user
    user_permissions_ids = []

    is_gym_admin_or_personal = user.is_superuser and user.contract
    if is_gym_admin_or_personal:
        for package_permission in user.contract.package.permissions.all():
            user_permissions_ids.append(package_permission.id)
    else:
        user_permissions_ids = user.get_all_permissions_ids()

    ids = ""
    for permission_id in user_permissions_ids:
        if ids:
            ids += ", "
        ids += str(permission_id)

    cursor = connection.cursor()
    cursor.execute("SELECT DISTINCT mm.name, m.name, ct.model FROM core_menu m "
                   "LEFT JOIN core_mainmenu mm ON m.mainmenu_id = mm.id "
                   "LEFT JOIN core_action a2 ON a2.menu_id = m.id "
                   "LEFT JOIN auth_permission p ON p.id = a2.permission_id "
                   "LEFT JOIN django_content_type ct ON ct.id = p.content_type_id "
                   "WHERE m.id IN( SELECT a.menu_id FROM core_action a WHERE a.permission_id IN(%s) )" % ids)
    rows = cursor.fetchall()

    menus = {}
    for row in rows:
        main_menu = row[0]
        menu = row[1]
        model = row[2]
        if not main_menu in menus:
            menus[main_menu] = []
        menus[main_menu].append({"menu": menu, "model": model})

    return menus

def paginator(form, page):
    if not page:
        page = 1
    paginator = Paginator(form.model, 10)
    try:
        paginated_object = paginator.page(page)
    except PageNotAnInteger:
        paginated_object = paginator.page(1)
        page = 1
    except EmptyPage:
        paginated_object = paginator.page(paginator.num_pages)
        page = paginator.num_pages
    next_page = int(page) + 1
    previous_page = int(page) - 1

    return next_page, previous_page, paginated_object